<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2018-06-07
 * Time: 13:42
 */

namespace app\api\model;

use app\api\service\Token as TokenService;

class Active extends BaseModel
{
    protected $table = 'we_activity';
    protected $hidden = [];

    // 自动写入时间戳
    // protected $autoWriteTimestamp = true;
    // 设置自动写入时间的格式
    protected $autoWriteTimestamp = 'datetime';

    // 读取器
    public function getUrlAttr($value){
        $finalUrl = $value;
        if(substr($value,0,4) === 'http'){
            return $finalUrl;
        }else{
            $finalUrl = config('setting.medisum_img_prefix').$value;
        }
        return $finalUrl;
    }

    // 根据活动id获取该活动信息
    public static function getActiveById($id)
    {
        $uid = TokenService::getCurrentUid();
        $user = User::where('id', '=', $uid)->find();
        $lottery_count = $user->lottery_count;
        $mans = User::count();
        $active = self::with([
                'prizes' => function($query){
                    $query->order('type', 'asc');
                }
            ])->where('status', '=', 1)->whereNull('delete_time')->find($id);
        $active->uid = $uid;
        $active->lottery_count = $lottery_count;
        $active->mans = $mans;
        return $active;
    }

    // 关联奖品表 多对多
    public function prizes(){
        return $this->belongsToMany('Prize', 'we_activity_prize', 'prizeId','activityId');
    }

}